//
//  JDNewSaleListViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2025/9/7.
//

import UIKit
import DZNEmptyDataSet

//class CustomCollectionView: UICollectionView {
//    private let contentBackgroundView = UIView()
//
//    override func layoutSubviews() {
//        super.layoutSubviews()
//        // 动态更新背景视图的尺寸
//        contentBackgroundView.frame = CGRect(
//            x: 0,
//            y: 0,
//            width: contentSize.width,
//            height: max(contentSize.height, bounds.height)
//        )
//    }
//
//    func setup() {
//        backgroundColor = .green // 无内容部分的背景色
//        contentBackgroundView.backgroundColor = .white // 有内容部分的背景色
//        backgroundView = contentBackgroundView
//    }
//}

class JDNewSaleListViewController: JDBaseViewController {
    
//    var customTitleView: CustomTitleView?
    /// 原来是区分 跨境直销和境外预售的  暂时无用
    var titleType: String = "4"
//    var countryName = ["全部","日本","韩国","泰国"]
//    var countryCode = ["all","jp","kr","th"]
    
    
//    var countryImage = ["country_all","country_ja-jp","country_ ko-kr","country_en-th"]
    var needRefreshClassification = true
    
    /// 分类部分
    var classificationView: DraClassicHeadView?
//    var goodsTypeTitleList: [String] = ["全部"]
//    var goodsTypeModels :[JDGoodsTypeModel?]?
    var goodsModels: [JDGoodsModel?]?
    
    var gradientView: UIView?
    
    
    //   -- - - - - - - - - - -- -分割线 - - - - - - -- - - - - -
    // 存储分类数据 用于跳转的时候使用
    var goodsTypeModels :[JDGoodsTypeModel?]?
    // 选中的分类的code
    var categoryCode = ""
    var countrySelectedIndex = 0
    var countryModels: [JDCountryInfoModel?]?
    var countryView: JDCountryTypeView = {
        let country = JDCountryTypeView()
        return country
    }()

    lazy var newCustonTitleView: JDNewCustomTitleView = {
        let newCustonTitle = JDNewCustomTitleView()
        return newCustonTitle
    }()
    
    lazy var mainCollectionView: UICollectionView = {

        // 创建自定义布局
        let layout = XLPlainFlowLayout()
        layout.itemSize = CGSizeMake(floor((screenWidth-10.0-24.0)/2.0), floor((screenWidth-10.0-24.0)/2.0)+131)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)
        layout.naviHeight = -90
        
        layout.onStickyStateChange = { [weak self] section, isSticky in
            self?.fakeView.selectedIndex = self?.typeView.selectedIndex ?? 0
            self?.fakeView.typeModels = self?.typeView.typeModels
            if isSticky {
                print("开始悬停")
                self?.fakeView.isHidden = false
            } else {
                print("不悬停了")
                self?.fakeView.isHidden = true
            }
        }
        
        let mainCollection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        mainCollection.delegate = self
        mainCollection.dataSource = self
        mainCollection.register(JDNewSaleCollectionViewCell.self, forCellWithReuseIdentifier: "myCell")
        mainCollection.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView")
        mainCollection.backgroundColor = color("#F5F5F5")
        
        mainCollection.emptyDataSetSource = self
        mainCollection.emptyDataSetDelegate = self
        
        return mainCollection
    }()
    
    lazy var typeView: JDTypeCollectionView = {
        let type = JDTypeCollectionView()
        return type
    }()
    
    lazy var fakeView: JDHomeTypeFakeView = {
        let fake = JDHomeTypeFakeView()
        fake.isHidden = true
        return fake
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupConfig()
        self.setupUIElements()
        // 请求国家
        self.getCountryCodeList()
        // 请求类型
        self.getClassificationData()
        self.getNetData(true)
        
        self.typeView.didChangeTypeCallBack = { [weak self] currentModel in
            guard let weakSelf = self else { return }
            weakSelf.categoryCode = currentModel?.id ?? ""
            weakSelf.getNetData(true)
        }
        
        self.typeView.gotoclassificationDetailCallBack = { [weak self] in 
            
            guard let weakSelf = self else { return }
            
            if !JDTools.checkToken() {
                return
            }
            let classilicationVC = JDClassificationViewController()
            classilicationVC.goodsTypeModels = weakSelf.goodsTypeModels
            weakSelf.hidesBottomBarPushViewController(classilicationVC)
            classilicationVC.selectedClassificationCompleted = {[weak self] classificationIndex ,selectedId in
                guard let classificationId = selectedId else { return }
                guard let weakSelf = self else { return }
                weakSelf.typeView.selectedIndex = classificationIndex+1
                weakSelf.typeView.mainCollectionView.reloadData()
                weakSelf.categoryCode = classificationId
                weakSelf.getNetData(true)
            }
            
        }
        
        self.createShopcartButton()
        
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        
        self.customNavigationBar?.frame = CGRectMake(self.customNavigationBar?.frame.origin.x ?? 0, self.customNavigationBar?.frame.origin.y ?? 0, self.customNavigationBar?.frame.width ?? 0, 119-44)

        self.customNavigationBar?.isHidden = true

        
        
    }
    
    func setupUIElements() {
        
        self.view.addSubview(self.newCustonTitleView)
        self.newCustonTitleView.snp.makeConstraints { make in
            make.bottom.equalTo(self.customNavigationBar!)
//            make.leading.trailing.equalTo(self.view)
            make.centerX.equalTo(self.customNavigationBar!)
            make.size.equalTo(CGSizeMake(screenWidth, UIDevice().safeAreaInset.top+13))
        }
        self.view.bringSubviewToFront(self.newCustonTitleView)
        
//        self.newCustonTitleView.layoutSubviews()
//        self.newCustonTitleView.layoutIfNeeded()
        
        self.newCustonTitleView.searchButton.addTarget(self, action: #selector(searchButtonAction), for: .touchUpInside)
        
        
        let countryView = self.createHeaderView()
        self.view.addSubview(countryView)
        countryView.snp.makeConstraints { make in
            make.leading.trailing.equalTo(self.view)
            make.top.equalTo(self.newCustonTitleView.snp.bottom).offset(-13)
            make.height.equalTo(51)
        }
        
        self.view.addSubview(self.mainCollectionView)
        self.mainCollectionView.snp.makeConstraints { make in
//            make.top.equalTo(self.newCustonTitleView.snp.bottom).offset(-13)
            make.top.equalTo(countryView.snp.bottom)
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view)
        }
        self.navigationController?.view.bringSubviewToFront(self.mainCollectionView)
//        self.mainCollectionView.backgroundColor = .commonColor()
        
//        self.mainCollectionView.contentInset = UIEdgeInsets(top: 51, left: 0, bottom: 0, right: 0)
//        let headerView = self.createHeaderView()
//        self.mainCollectionView.addSubview(headerView)
//        headerView.frame = CGRectMake(0, -51, screenWidth, 51)
        
        self.view.addSubview(self.fakeView)
        self.fakeView.snp.makeConstraints { make in
            make.leading.trailing.equalTo(self.view)
//            make.top.equalTo(self.newCustonTitleView.snp.bottom).offset(-13)
            make.top.equalTo(countryView.snp.bottom)
            make.height.equalTo(90+33+1)
        }
        self.fakeView.layoutSubviews()
        fakeView.changeClassificationCallBack = { [weak self] selectedIndex ,currentModel in
            guard let weakSelf = self else { return }
            weakSelf.categoryCode = currentModel?.id ?? ""
            weakSelf.getNetData(true)
            
            weakSelf.typeView.selectedIndex = selectedIndex
            weakSelf.typeView.mainCollectionView.reloadData()
            
            weakSelf.mainCollectionView.scrollToItem(at: IndexPath.init(item: 0, section: 0), at: .top, animated: true)
            
        }
        
        fakeView.gotoClassificationDetailCallBack = { [weak self] in
            
            guard let weakSelf = self else { return }
            
            if !JDTools.checkToken() {
                return
            }
            let classilicationVC = JDClassificationViewController()
            classilicationVC.goodsTypeModels = weakSelf.goodsTypeModels
            weakSelf.hidesBottomBarPushViewController(classilicationVC)
            classilicationVC.selectedClassificationCompleted = {[weak self] classificationIndex ,selectedId in
                guard let classificationId = selectedId else { return }
                guard let weakSelf = self else { return }
                weakSelf.typeView.selectedIndex = classificationIndex+1
                weakSelf.typeView.mainCollectionView.reloadData()
                weakSelf.categoryCode = classificationId
                weakSelf.getNetData(true)
            }
        }
        
//        self.view.bringSubviewToFront(self.mainCollectionView)
        
        self.mainCollectionView.addRefreshHeader(ignoredTopInset: 51-13+5) { [weak self] in
            if self?.needRefreshClassification ?? true {
                self?.getClassificationData()
            }
            self?.currentPage = 1
            self?.getNetData(true)
        }
        
        self.mainCollectionView.addRefreshFooter { [weak self] in
            self?.currentPage += 1
            self?.getNetData(false)
        }
        
    }
    
    @objc func memberAreaAction() {
        if !JDTools.checkToken() {
            return
        }
        let memberAreaVC = JDMemberAreaViewController()
        memberAreaVC.goodsModels = self.goodsModels
        memberAreaVC.goodsTypeModels = self.goodsTypeModels
        self.hidesBottomBarPushViewController(memberAreaVC)
    }
    
    
    @objc func searchButtonAction() {
        printLog("搜索按钮")
        if !JDTools.checkToken() {
            return
        }
        
        let searchVC = JDSearchViewController()
        searchVC.modalPresentationStyle = .none
        let navSearchVC = UINavigationController(rootViewController: searchVC)
        self.presentVC(navSearchVC)
        
    }
    
    func getCountryCodeList() {
        JDNetWorkRequest(.getCountryCodeList) { responseStr in
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                print("先看看，返回的是什么:\(responseStr)")
                
                if let models = [JDCountryInfoModel].deserialize(from: responseStr, designatedPath: "data") {
                    
                    self.countryModels = models
                    self.countryView.countryModels = self.countryModels
                    self.countryView.mainCollectionView.reloadData()
                    printLog("我已经请求成功:\(models)")
                    
//                    if isRefresh {
//                        self.goodsModels = models
//                    } else {
//                        self.goodsModels?.append(contentsOf: models)
//                    }
//
//                    if models.count < 10 {
//                        self.mainTableView?.noMoreData()
//                    }
                } else {
                    self.view.toast(message: "异常数据")
                }
            } else {
                self.view.toast(message: commonModel?.msg ?? "网络异常")
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }

    }
    
    @objc func getClassificationData() {
        
        JDNetWorkRequest(.getGoodsType([:])) { responseStr in
            
            printLog("分类信息:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                if let models = [JDGoodsTypeModel].deserialize(from: responseStr, designatedPath: "data") {
                     
                    self.goodsTypeModels?.removeAll()
                    self.goodsTypeModels = models
                    
                    self.typeView.typeModels.removeAll()
                    
                    let allModel = JDGoodsTypeModel()
                    allModel.name = "全部"
                    allModel.logo = "product_type_all"
                    
                    let classificationModel = JDGoodsTypeModel()
                    classificationModel.name = "分类"
                    classificationModel.logo = "product_type_classification"
                    
                    
                    self.typeView.typeModels.append(allModel)
                    self.typeView.typeModels.append(contentsOf: models)
                    self.typeView.typeModels.append(classificationModel)
                    
//                    self.typeView.typeModels = models
                    self.typeView.mainCollectionView.reloadData()
                    
                    self.needRefreshClassification = false

                }
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }
    }
    
    
    override func getNetData(_ isRefresh: Bool = true) {
        
        var params = [String: Any]()
        // 国家代码
        params["countryCode"] = self.countryModels?[self.countrySelectedIndex]?.countryCode?.lowercased()//self.countryCode[self.countrySelectedIndex]
        // 商品分类 -- 这个还要改
        if self.categoryCode.count > 0 {
            params["goodsCategory"] = self.categoryCode
        }
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10
        params["goodsMemberLevel"] = 1
        if isRefresh {
            self.goodsModels?.removeAll()
        }
        self.showLoading()
        print("商品列表接口:\(params)")
        JDNetWorkRequest(.getGoodsList(params)) { responseStr in
            self.dismissLoading()
            self.mainCollectionView.mj_header?.endRefreshing()
            self.mainCollectionView.mj_footer?.endRefreshing()
            printLog("商品列表信息:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                if let models = [JDGoodsModel].deserialize(from: responseStr, designatedPath: "data.records") {
                    
                    if isRefresh {
                        self.goodsModels = models
                    } else {
                        self.goodsModels?.append(contentsOf: models)
                    }
                    
                    if models.count < 10 {
                        self.mainCollectionView.noMoreData()
                    }
                } else {
                    self.view.toast(message: "异常数据")
                }
            } else {
                self.view.toast(message: commonModel?.msg ?? "网络异常")
            }
            self.mainCollectionView.reloadData()
        } failure: { error in
            self.view.toast(message: "网络异常")
            self.dismissLoading()
            self.mainCollectionView.mj_header?.endRefreshing()
            self.mainCollectionView.mj_footer?.endRefreshing()
        } error: { errorCode in
            self.view.toast(message: "网络异常")
            self.dismissLoading()
            self.mainCollectionView.mj_header?.endRefreshing()
            self.mainCollectionView.mj_footer?.endRefreshing()
        }

    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDNewSaleListViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.goodsModels?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as? JDNewSaleCollectionViewCell
        
        let currentModel = self.goodsModels?[indexPath.row]
        cell?.updateDate(currentModel)
        
        return cell!
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSizeMake(floor((screenWidth-10.0-24.0)/2.0), floor((screenWidth-10.0-24.0)/2.0)+131)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return .init(top: 0, left: 12, bottom: 0, right: 12)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSizeMake(screenWidth, 90*2+33+1)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView", for: indexPath)
            
            headerView.addSubview(self.typeView)
            self.typeView.snp.makeConstraints { make in
                make.leading.trailing.top.bottom.equalTo(headerView)
            }
            
            return headerView
        }
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        guard let goodsModel = self.goodsModels?[indexPath.row] else {
            return
        }
        let goodsDetailVC = JDGoodsDetailViewController()
        goodsDetailVC.goodsLogoUrl = goodsModel.goodsMainImgUrl
        goodsDetailVC.goodsID = goodsModel.goodsId
        self.hidesBottomBarPushViewController(goodsDetailVC)

    }
}

//MARK: - DZNEmptyDataSet
extension JDNewSaleListViewController: DZNEmptyDataSetSource,DZNEmptyDataSetDelegate {
    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        return UIImage(named: "emptyView")
    }
    
    func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
        return 90+12 // 默认是垂直居中，这里整体往上移 30pt
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        let text = "暂无商品"
        let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16.0),
                          NSAttributedString.Key.foregroundColor: color("#999999")]
        return NSAttributedString(string: text, attributes: attributes as [NSAttributedString.Key : Any])
    }

}
